package com.tingyuge.base.jdk.io.nio.datagram;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2022/1/9
 * @description
 */
public class DatagramChannelDemo {

    /***
     * test send
     */
    @Test
    public void sendDataGram() throws Exception {
        DatagramChannel datagramChannel = DatagramChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 9999);
        while (true) {
            ByteBuffer buffer = ByteBuffer.wrap("发送 udp".getBytes(Charset.defaultCharset()));
            datagramChannel.send(buffer, inetSocketAddress);
            System.out.println("已经完成发送");
            Thread.sleep(1000);
        }
    }

    @Test
    public void receiveDataGram() throws IOException {
        DatagramChannel datagramChannel = DatagramChannel.open();
        DatagramChannel channel = datagramChannel.bind(new InetSocketAddress("127.0.0.1", 9999));
        System.out.println(datagramChannel == channel);

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //接受
        while (true) {
            buffer.clear();
            SocketAddress socketAddress = datagramChannel.receive(buffer);
            buffer.flip();
            System.out.println(socketAddress.toString());
            System.out.println("接受消息: " + Charset.forName("UTF-8").decode(buffer));
        }
    }


    /**
     * 连接
     */

    @Test
    public void testConnect() throws Exception {
        DatagramChannel datagramChannel = DatagramChannel.open();
        datagramChannel.bind(new InetSocketAddress("127.0.0.1", 9999));
        //连接
        datagramChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
        //write
        ByteBuffer buffer = ByteBuffer.wrap("发送 udp".getBytes(Charset.defaultCharset()));
        datagramChannel.write(buffer);

        //read
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        while (true){
            readBuffer.clear();
            datagramChannel.read(readBuffer);
            readBuffer.flip();
            System.out.println("接受消息: " + Charset.forName("UTF-8").decode(readBuffer));
            Thread.sleep(2000);

        }
    }

}
